<template>
  <n-modal
    preset="card"
    style="width: 800px"
    :mask-closable="false"
    :close-on-esc="false"
    :title="isIns ? '新增' : '修改'"
    :show="show"
    :on-after-enter="init"
    :on-after-leave="destroy"
    @close="close"
  >
    <n-form label-width="auto" label-placement="left" ref="formRef" :model="form" :rules="rules">
      <n-form-item label="字典" path="code" show-require-mark>
        <n-input v-model:value="form.code" :disabled="!isIns" />
      </n-form-item>
      <n-form-item label="名称" path="name" show-require-mark>
        <n-input v-model:value="form.name" />
      </n-form-item>
      <n-form-item label="状态" path="status" show-require-mark>
        <n-radio-group v-model:value="form.status">
          <n-radio
            :label="item.label"
            :value="item.value"
            :key="item.value"
            v-for="item in codeStore.getCodesByDict(_Dict.Status)"
          />
        </n-radio-group>
      </n-form-item>
      <n-form-item label="备注">
        <n-input type="textarea" v-model:value="form.remark" />
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="close">关闭</n-button>
        <n-button type="info" @click="handleConfirmOnClick">确认</n-button>
      </n-space>
    </template>
  </n-modal>
</template>
<script lang="ts" setup>
import { getDict, postOrPutDict } from '@/api/system/Dict'

const codeStore = useCodeStore()

const props: IFormProps<SystemDictPO> = defineProps({
  show: {
    type: Boolean
  },
  po: {
    type: Object as PropType<SystemDictPO>,
    required: true
  }
})

const emits = defineEmits<{
  (e: 'handleCloseOnClick'): void
  (e: 'handleSelectOnClick'): void
}>()

const state = reactive<IFormState<SystemDictPO>>({
  isIns: false,
  form: {} as SystemDictPO
})

const { isIns, form } = toRefs(state)

const formRef = ref()

const rules: FormRules = {
  code: [
    {
      required: true
    }
  ],
  name: [
    {
      required: true
    }
  ],
  status: [
    {
      required: true
    }
  ]
}

const init = async () => {
  state.isIns = Object.keys(props.po).length == 0
  if (state.isIns) return
  const { data } = await getDict(props.po.id)
  state.form = data
}

const handleConfirmOnClick = async () => {
  formRef.value?.validate(async (errors: any) => {
    if (errors) return
    await postOrPutDict(state.form)
    select()
    close()
  })
}

const select = () => {
  emits('handleSelectOnClick')
}

const close = () => {
  emits('handleCloseOnClick')
}

const destroy = () => {
  Object.keys(state.form).forEach((key) => {
    state.form[key] = null
  })
}
</script>
